package com.by.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class TraceIdFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        List<String> traceIds = request.getHeaders().get("traceId");
        if(ObjectUtil.isNotEmpty(traceIds)){
            return chain.filter(exchange);
        }
        String traceId = IdUtil.simpleUUID();
        ServerHttpRequest request2 = request.mutate().header("traceId", traceId).build();
        ServerWebExchange  exchange2 = exchange.mutate().request(request2).build();
        return chain.filter(exchange2);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
